﻿using OpenProgramUpdateSDK.Core;
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace OpenProgramUpdateSDK.Impl
{
    class UpdateManager : IUpdateManager
    {
        private string ProgramPath = "";
        private string[] ForbiddenList;
        private const string HTTPH = "http://";
        private const string HTTPSH = "https://";
        private bool needLaunch = false;
        public string HostFullName { get; private set; }
        public ProgressBar ProgressBarObject { get; private set; }

        NewListUpdateClass nluc = new NewListUpdateClass();
        /// <summary>
        /// 开始更新
        /// </summary>
        public void UpdateStart()
        {
            //关闭原有的应用程序

            if (nluc.CheckList(HostFullName))
            {
                //新的下载更新方法
                //progressBar1.Maximum = nluc.TodoDwnFile.Count;
                nluc.TodoDwnFile.ForEach(new Action<Core.dltype>((Core.dltype s) => {
                    //curnlabel4.Text = s.path;
                    if (CanDownload(s.path))
                    {
                        DownloadFile(s.url, AppDomain.CurrentDomain.BaseDirectory + s.path, ProgressBarObject);
                    }
                    //progressBar1.Value++;
                }));
            }
            else
            {

            }
            if (MessageBox.Show("升级完成！请重新登陆！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
            {
                if (needLaunch)
                {
                    FileInfo file = new FileInfo(ProgramPath);//文件地址
                    if (file.Exists)
                    {
                        Process.Start(ProgramPath);
                    }
                }
                
                //Application.Exit();
            }
        }
        /// <summary>        
		/// c#.net 下载文件        
		/// </summary>        
		/// <param name="URL">下载文件地址</param>       
		/// 
		/// <param name="Filename">下载后的存放地址</param>        
		/// <param name="Prog">用于显示的进度条</param>        
		/// 
		private void DownloadFile(string URL, string filename, ProgressBar prog,Label label1 = null)
        {
            float percent = 0;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);

                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    if (label1!=null)
                    {
                        label1.Text = "下载进度" + percent.ToString() + "%";
                    }
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                if (label1 != null)
                {
                    label1.Text = "下载完成。安装中... ...";
                }  
                so.Flush();//将缓冲区内在写入到基础流中
                st.Flush();//将缓冲区内在写入到基础流中
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {

            }
        }

        /// <summary>
        /// 判断是否可以下载
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool CanDownload(string path)
        {
            if (ForbiddenList!=null && ForbiddenList.Length>0)
            {
                foreach (string item in ForbiddenList)
                {
                    if (Regex.IsMatch(path, item, RegexOptions.IgnoreCase))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        public void KillProess(string ProgramName)
        {
            System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName(ProgramName);
            //关闭原有应用程序的所有进程
            foreach (System.Diagnostics.Process pro in proc)
            {
                pro.Kill();
            }
        }

        public void Init(string ProgramPath, string ChannelName, string[] ForbiddenFiles,ProgressBar ProgressBarObject,string Host = null, int port = 80)
        {
            this.ProgramPath = ProgramPath;
            this.ForbiddenList = ForbiddenFiles;
            if (Host!=null && Host!="")
            {
                if (!Host.Contains(HTTPH))
                {
                    Host = HTTPH + Host;
                }
                HostFullName = Host+":"+port.ToString();
            }
            nluc.project = ChannelName;
            this.ProgressBarObject = ProgressBarObject;
        }

        public void SetLaunchAfterUpdate()
        {
            if (this.ProgramPath!=null && this.ProgramPath!="")
            {
                needLaunch = true;
            }
        }
    }
}
